<template>
  <div>
    <quill-editor
      class="quill-editor"
      v-loading="loading.upload"
      ref="QuillEditor"
      v-model="content"
      :style="style"
      :options="options"
    ></quill-editor>
    <el-upload
      action="/"
      class="quill-uploadImage__warp"
      multiple
      :limit="1"
      :file-list="fileList"
      accept="image/png, image/jpeg"
      :show-file-list="false"
      :http-request="uploadFile"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
let quillEditor;
if (process.browser) {
  const editor = require("vue-quill-editor");
  quillEditor = editor.quillEditor;
}
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],
  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  // [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction
  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [
    {
      font: [
        "SimSun",
        "SimHei",
        "Microsoft-YaHei",
        "KaiTi",
        "FangSong",
        // "Arial",
        // "Times-New-Roman",
        // "sans-serif"
      ],
    },
  ],
  [{ align: [] }],
  ["link", "image"],
  ["clean"], // remove formatting button
];

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import PhotoCompress from "@/assets/js/photo_compress";
import { compress, getBase64 } from "@/assets/js/compress";
const maxSize = 0.5 * 1024 * 1024; // 0.5M
const minSize = 0; // 200K
const photoCompress = new PhotoCompress(minSize, maxSize);
export default {
  name: "FuncFormsEdit",
  components: {
    quillEditor,
  },
  computed: {
    style() {
      return `height:${this.height}px;padding-bottom: 82px;`;
    },
  },
  props: ["value", "option", "height"],
  data() {
    return {
      loading: {
        upload: false,
      },
      fileList: [],
      content: this.value,
      options: {
        ...this.option,
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: (value) => {
                if (value) {
                  document
                    .querySelector(".quill-uploadImage__warp input")
                    .click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  watch: {
    content(val) {
      this.content = val;
      this.$emit("update:value", this.content);
    },
    value() {
      this.content = this.value;
    },
  },
  methods: {
    // 图片上传成功
    async uploadFile(res) {
      this.loading.upload = true;
      let base64 = await this.imgBase64(res.file);
      let compressBase64 = await this.compress(base64);
      let newFile = photoCompress.dataBase64ToFile(
        compressBase64,
        res.file.name
      );
      let file = new File([newFile], res.file.name, { type: res.file.type });
      if (file.size < 1 * 1024 * 1024) {
        let formData = new FormData();
        formData.append("file", file);
        try {
          let data = await this.$axios.post("/admin/tool/update", formData);
          let quill = this.$refs.QuillEditor.quill;
          let length = quill.getSelection().index;
          quill.insertEmbed(length, "image", data.data.url);
          quill.setSelection(length + 1);
        } catch (error) {
          console.error(error);
        }
      } else {
        this.$message({
          message: `图片过大，无法上传，请重新选择，建议选1M以下`,
          type: "error",
        });
      }
      this.fileList = [];
      this.loading.upload = false;
    },
    imgBase64(file) {
      return new Promise((resolve, reject) => {
        getBase64(file, (base64) => {
          resolve(base64);
        });
      });
    },
    compress(oldBase64) {
      let quality = 0.5;
      if (this.showSize(oldBase64) > 4 * 1024) {
        quality = 0.1;
      }
      return new Promise((resolve, reject) => {
        compress(
          oldBase64,
          {
            quality: quality,
          },
          (base64) => {
            resolve(base64);
          }
        );
      });
    },
    showSize(base64url) {
      //把头部去掉
      let str = base64url.replace("data:image/png;base64,", "");
      // 找到等号，把等号也去掉
      let equalIndex = str.indexOf("=");
      if (str.indexOf("=") > 0) {
        str = str.substring(0, equalIndex);
      }
      // 原来的字符流大小，单位为字节
      let strLength = str.length;
      // 计算后得到的文件流大小，单位为字节
      let fileLength = parseInt(strLength - (strLength / 8) * 2);
      // 由字节转换为kb
      let size = "";
      size = (fileLength / 1024).toFixed(2);
      let sizeStr = size + ""; //转成字符串
      let index = sizeStr.indexOf("."); //获取小数点处的索引
      let dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值
      if (dou == "00") {
        //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
      }
      return size;
    },
  },
};
</script>

<style  lang="scss" scoped>
.quill-uploadImage__warp {
  width: 0;
  height: 0;
  display: none;
}
.quill-editor /deep/ {
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="SimSun"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="SimSun"]::before {
    content: "宋体";
    font-family: "SimSun" !important;
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="SimHei"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="SimHei"]::before {
    content: "黑体";
    font-family: "SimHei" !important;
  }
  .ql-snow
    .ql-picker.ql-font
    .ql-picker-label[data-value="Microsoft-YaHei"]::before,
  .ql-snow
    .ql-picker.ql-font
    .ql-picker-item[data-value="Microsoft-YaHei"]::before {
    content: "微软雅黑";
    font-family: "Microsoft YaHei";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="KaiTi"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="KaiTi"]::before {
    content: "楷体";
    font-family: "KaiTi" !important;
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="FangSong"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="FangSong"]::before {
    content: "仿宋";
    font-family: "FangSong";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="Arial"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="Arial"]::before {
    content: "Arial";
    font-family: "Arial";
  }
  .ql-snow
    .ql-picker.ql-font
    .ql-picker-label[data-value="Times-New-Roman"]::before,
  .ql-snow
    .ql-picker.ql-font
    .ql-picker-item[data-value="Times-New-Roman"]::before {
    content: "Times New Roman";
    font-family: "Times New Roman";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="sans-serif"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="sans-serif"]::before {
    content: "sans-serif";
    font-family: "sans-serif";
  }
}
</style>